package com.dangz.dans.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dangz.dans.entity.CommonResponse;
import com.dangz.dans.model.req.TrainsReq;
import com.dangz.dans.model.resp.TrainsInfo;
import com.dangz.dans.response.ApiEnum;
import com.dangz.dans.response.CodeEnum;
import com.dangz.dans.response.TypeEnum;
import com.dangz.dans.utils.CnToSpell;
import com.dangz.dans.utils.HttpHander;
import com.dangz.dans.utils.TrainsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author dangz
 * @since 2018/1/24 10:36
 */
@RestController
@RequestMapping("dans/trains")
@Api(tags = "票务")
public class TrainsController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ApiOperation(value = "查询单程票务信息", notes = "POST方式")
    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "header", value = "Authorization", name = HttpHeaders.AUTHORIZATION, dataType = "String")
            @ApiImplicitParam(paramType = "query", name = "departureCityName", value = "始发地", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "arrivalCityName", value = "目的地", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "departureDate", value = "出发日期", dataType = "String", required = true)
    })
    @PostMapping("findByTickets")
    public CommonResponse findByCode(String departureCityName, String arrivalCityName, String departureDate){
        CommonResponse commonResponse = null;
        //请求信息
        TrainsReq trains = new TrainsReq();
        trains.setArrivalCity(CnToSpell.getSpell(arrivalCityName, false ));
        trains.setDepartureCity(CnToSpell.getSpell(departureCityName, false ));
        trains.setArrivalCityName(arrivalCityName);
        trains.setDepartureCityName(departureCityName);
        trains.setDepartureDate(departureDate);
        JSONObject obj = new JSONObject();
        obj.put("value", JSON.toJSONString(trains));
        List<TrainsInfo> trainsInfos = new ArrayList<>();
        TrainsInfo trainsInfo = null;
        try {
            String str = HttpHander.doPost(TrainsUtils.POST_URL, obj);
            obj = JSONObject.parseObject(str);
            JSONArray resultS = JSONObject.parseArray(obj.get("TrainItemsList").toString());
            JSONArray seatBookingItemObj = new JSONArray();
            JSONObject seatInfo = null;
            List<JSONObject> seatInfos = null;
            for (Object o : resultS) {
                obj = (JSONObject) o;
                trainsInfo = new TrainsInfo();
                seatInfos = new LinkedList<>();
                /*logger.info("result:{}", obj.toJSONString());
                logger.info("EndStationName(目的地):{}, EndTime(到站时间):{}, StartStationName(始发站)：{}, TakeTime(运行时间):{}, " +
                                "StratTime(发车时间):{}", obj.get("EndStationName"), obj.get("EndTime"),
                        obj.get("StartStationName"), obj.get("TakeTime"), obj.get("StratTime"));*/

                trainsInfo.setEndStationName(obj.getString("EndStationName"));
                trainsInfo.setEndTime(obj.getString("EndTime"));
                trainsInfo.setStartStationName(obj.getString("StartStationName"));
                trainsInfo.setTakeTime(obj.getString("TakeTime"));
                trainsInfo.setStartTime(obj.getString("StratTime"));
                trainsInfo.setTrainName(obj.getString("TrainName"));

                seatBookingItemObj = JSON.parseArray(obj.get("SeatBookingItem").toString());
                for (Object seatObj : seatBookingItemObj) {
                    obj = (JSONObject) seatObj;
                    seatInfo = new JSONObject();
                    seatInfo.put("seatName", obj.getString("SeatName"));
                    seatInfo.put("price", obj.getString("Price"));
                    seatInfo.put("inventory", obj.getString("Inventory"));
                    seatInfos.add(seatInfo);
                   /*logger.info("SeatName:{}, Price(价格):{}, Inventory(余票):{}",
                            obj.get("SeatName"), obj.get("Price"),  obj.get("Inventory"));*/
                }
                trainsInfo.setSeatBookingItems(seatInfos);
                trainsInfos.add(trainsInfo);
            }
            if (trainsInfos.size() == 0) {
                commonResponse =  new CommonResponse<>(TypeEnum.getFullRespCode(TypeEnum.Success, ApiEnum.CS001,
                        CodeEnum.SUCCESS_NO_DATA_LOCAL), CodeEnum.SUCCESS_NO_DATA_LOCAL.getInfo(), false);
            } else {
                commonResponse =  new CommonResponse<>(TypeEnum.getFullRespCode(TypeEnum.Success, ApiEnum.CS001,
                        CodeEnum.SUCCESS_LOCAL), CodeEnum.SUCCESS_LOCAL.getInfo(), trainsInfos);
            }

        }   catch (Exception e) {
            e.printStackTrace();
            logger.error("查询单程票务信息异常……");
            commonResponse =  new CommonResponse<>(TypeEnum.getFullRespCode(TypeEnum.Error,
                    ApiEnum.CS001, CodeEnum.FAIL_SERVICE_LOCAL), CodeEnum.FAIL_SERVICE_LOCAL.getInfo());
        }
        return commonResponse;
    }
}
